import React, { useState, useEffect } from 'react';
import { Input, Carousel, Row, Col, Card, Typography, Button, message } from 'antd';
import { SearchOutlined, ShoppingCartOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { Product } from '../../types';
import { mockProducts } from '../../services/mockData';
import { CartItem } from '../../types';
import { Storage, STORAGE_KEYS } from '../../utils/storage';
import { SearchService } from '../../services/searchService';

const { Title, Text } = Typography;
const { Search } = Input;

const Home: React.FC = () => {
  const [hotProducts, setHotProducts] = useState<Product[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const navigate = useNavigate();

  useEffect(() => {
    // 获取热门商品
    const hot = mockProducts.filter(product => product.isHot);
    setHotProducts(hot);
  }, []);

  const handleSearch = (value: string) => {
    if (!value.trim()) {
      message.warning('请输入搜索关键词');
      return;
    }
    
    const results = SearchService.searchProducts(value);
    if (results.length === 0) {
      message.info('没有找到相关商品');
    } else {
      // 跳转到分类页面并传递搜索结果
      navigate('/category', { state: { searchResults: results, keyword: value } });
    }
  };

  const handleProductClick = (productId: string) => {
    navigate(`/product/${productId}`);
  };

  const handleAddToCart = (product: Product, e: React.MouseEvent) => {
    e.stopPropagation();
    
    const cartItems = Storage.get<CartItem[]>(STORAGE_KEYS.CART) || [];
    const existingItem = cartItems.find(item => item.productId === product.id);
    
    if (existingItem) {
      existingItem.quantity += 1;
    } else {
      const newItem: CartItem = {
        id: Date.now().toString(),
        productId: product.id,
        product,
        quantity: 1,
        selected: true
      };
      cartItems.push(newItem);
    }
    
    Storage.set(STORAGE_KEYS.CART, cartItems);
    message.success('已添加到购物车');
  };

  const carouselImages = [
    'https://via.placeholder.com/800x300?text=轮播图1',
    'https://via.placeholder.com/800x300?text=轮播图2',
    'https://via.placeholder.com/800x300?text=轮播图3',
  ];

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto' }}>
      {/* 搜索框 */}
      <div style={{ marginBottom: 24 }}>
        <Search
          placeholder="搜索商品"
          allowClear
          enterButton={<SearchOutlined />}
          size="large"
          value={searchValue}
          onChange={(e) => setSearchValue(e.target.value)}
          onSearch={handleSearch}
          style={{ maxWidth: 500 }}
        />
      </div>

      {/* 轮播图 */}
      <div style={{ marginBottom: 32 }}>
        <Carousel autoplay>
          {carouselImages.map((image, index) => (
            <div key={index}>
              <img
                src={image}
                alt={`轮播图${index + 1}`}
                style={{
                  width: '100%',
                  height: 300,
                  objectFit: 'cover',
                  borderRadius: 8
                }}
              />
            </div>
          ))}
        </Carousel>
      </div>

      {/* 热门商品 */}
      <div>
        <Title level={2} style={{ marginBottom: 24 }}>
          🔥 热门商品
        </Title>
        
        <Row gutter={[16, 16]}>
          {hotProducts.map((product) => (
            <Col xs={12} sm={8} md={6} lg={6} key={product.id}>
              <Card
                hoverable
                className="product-card"
                cover={
                  <img
                    alt={product.name}
                    src={product.image}
                    style={{ height: 200, objectFit: 'cover' }}
                  />
                }
                actions={[
                  <Button
                    type="primary"
                    icon={<ShoppingCartOutlined />}
                    onClick={(e) => handleAddToCart(product, e)}
                  >
                    加购物车
                  </Button>
                ]}
                onClick={() => handleProductClick(product.id)}
              >
                <Card.Meta
                  title={
                    <Text ellipsis={{ tooltip: product.name }}>
                      {product.name}
                    </Text>
                  }
                  description={
                    <div>
                      <div style={{ marginBottom: 8 }}>
                        <span className="price-current">¥{product.price}</span>
                        {product.originalPrice && (
                          <span className="price-original">¥{product.originalPrice}</span>
                        )}
                      </div>
                      <Text type="secondary">已售 {product.sales}</Text>
                    </div>
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>
      </div>
    </div>
  );
};

export default Home;
